export function downLoadZip(res, title) {
  const blob = new Blob([res], { type: 'application/zip' });
  const downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  downloadElement.download = `${title}.zip`; // 下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href);
}

export function downLoadVideo(url, title) {
  url = url + '?&response-content-type=application%2Foctet-stream';
  const downloadElement = document.createElement('a');
  downloadElement.href = url;
  downloadElement.download = `${title}.mp4`;
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成移除元素
}

/** 函数防抖 */
export function debounce(fn, wait = 300) {
  var timer = null;
  return function(...args) {
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn(...args);
    }, wait);
  };
}

/** 函数节流 */
export function throttle(fn, wait = 300) {
  let locked = false;

  return function(...args) {
    if (locked) return;
    locked = true;
    setTimeout(() => {
      locked = false;
    }, wait);

    fn(...args);
  };
}

/** 数组去重 */
export function unique(arr) {
  if (!Array.isArray(arr)) {
    return console.error('type error!');
  }
  return [...new Set(arr)];
}

export function uniqueComplex(arr, fn) {
  if (!Array.isArray(arr) || typeof fn !== 'function') {
    return [];
  }
  let obj = {};
  arr.forEach((item) => {
    obj[fn(item)] = item;
  });

  return Object.values(obj);
}

const imagesList = [];
/** 测量图片的尺寸是否合格 */
export function measureImageInvalid(src, minWidth = 0, minHeight = 0) {
  return new Promise((resolve, reject) => {
    let img = imagesList.pop() || new Image();
    img.onload = () => {
      let valid = img.width >= minWidth && img.height >= minHeight;
      // console.log('图片==', img.width, img.height);
      if (valid) {
        resolve();
      } else {
        reject();
      }
      img.onload = null;
      imagesList.push(img);
    };
    img.src = src;
  });
}

/** 驼峰转下划线 */
export function toLine(name) {
  return name.replace(/([A-Z])/g, '_$1').toLowerCase();
}

/** 时间戳转年月日 时分*/
export function timeStampToDate(timestamp) {
  let time = new Date(timestamp);
  let year = time.getFullYear();
  let month = time.getMonth() + 1;
  let date = time.getDate();
  let hours = time.getHours();
  let minute = time.getMinutes();
  let second = time.getSeconds();

  if (month < 10) {
    month = '0' + month;
  }
  if (date < 10) {
    date = '0' + date;
  }
  if (hours < 10) {
    hours = '0' + hours;
  }
  if (minute < 10) {
    minute = '0' + minute;
  }
  if (second < 10) {
    second = '0' + second;
  }
  return year + '-' + month + '-' + date + ' ' + hours + ':' + minute;
}

export function isBlank(value) {
  return /\s/g.test(value);
}

/** 有效数字可为数字字符串 且不为空 */
export function isValidNumber(value) {
  if (value === '') return false;
  value = Number(value);
  return typeof value === 'number' && !isNaN(value);
};

// 最对保留几位小数
export function maxParts(v, num = 2) {
  v = String(v);
  if (!v) return true;
  return v.indexOf(".") == -1 || v.slice(v.indexOf(".") + 1).length <= num;
};

/** 异步请求更平滑一点 */
export function smoothAsyncHandler(p1, time = 500) {
  let p2 = new Promise((resove) => {
    setTimeout(resove, time);
  });
  return Promise.all([p1, p2]).then((args) => Promise.resolve(args[0]));
}

/** 异步请求超时处理 */
export function asyncTimeoutHandler(p1, time = 5000, text) {
  let p2 = new Promise((resove, reject) => {
    setTimeout(() => {
      reject(text || '请求超时，请重试');
    }, time);
  });
  return Promise.race([p1, p2]);
}

export function getVideoTimes(file) {
  return new Promise((resolve, reject) => {
    //获取录音时长
    var audioElement;
    var url;
    if (typeof file == 'string') {
      audioElement = new Audio();
      audioElement.src = file;
    } else {
      url = window.URL.createObjectURL(file);
      audioElement = new Audio(url);
    }

    audioElement.addEventListener('loadedmetadata', function(_event) {
      var duration = audioElement.duration;
      // console.log("视频时长", duration);
      window.URL.revokeObjectURL(url);

      resolve(duration);
    });
  });
}

/**是否是字符串 */
export function isString(v) {
  return Object.prototype.toString.call(v) === '[object String]';
}

/**是否是数字 */
export function isNumber(v) {
  return Object.prototype.toString.call(v) === '[object Number]';
}

/**
 * @description 判断是否是非空对象
 * @param {object} obj 对象
 * @return {boolean}
 */
export function isNotEmptyObj(obj) {
  if (obj && Object.keys(obj).length) {
    return true;
  } else {
    return false;
  }
}

// 手机号校验
export function phoneNumberCheck(number) {
  return /^1[0-9]{10}$/.test(number)
}

/** 取随机数 */
export function random(max) {
  return Math.round(Math.random() * max)
}

/** 参数格式化 */
export function queryFormat(str = '') {
  str = str.slice(str.indexOf('?') + 1);
  const querys = str.split('&').reduce((result, item) => {
    const arr = item.split('=');
    if (arr && arr.length === 2) {
      result[arr[0]] = arr[1];
    }
    return result;
  }, {});

  return querys;
}

